import 'package:flutter/material.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import 'package:concierge/generated/locales.g.dart';

/// 耳机操作弹窗
/// 用于显示耳机按键操作选择
class EarphoneActionDialog<T> extends StatefulWidget {
  /// 标题
  final String title;

  /// 已选择的操作
  final T? selectedAction;

  /// 操作列表
  final List<T> actions;

  /// 确认回调
  final Function(T?)? onConfirm;

  /// 取消回调
  final Function()? onCancel;
  
  /// 用于指定如何从T类型对象获取显示文本的回调
  final String Function(T) displayStringForOption;

  const EarphoneActionDialog({
    Key? key,
    required this.title,
    this.selectedAction,
    required this.actions,
    this.onConfirm,
    this.onCancel,
    required this.displayStringForOption,
  }) : super(key: key);

  @override
  State<EarphoneActionDialog<T>> createState() => _EarphoneActionDialogState<T>();
}

class _EarphoneActionDialogState<T> extends State<EarphoneActionDialog<T>> {
  /// 当前选中的操作
  T? _currentSelectedAction;
  
  /// 当前选中的索引
  late int _selectedIndex;

  @override
  void initState() {
    super.initState();
    // 初始化选中的操作
    _currentSelectedAction = widget.selectedAction;
    // 初始化选中的索引
    _selectedIndex = widget.selectedAction != null 
        ? widget.actions.indexWhere((element) => element == widget.selectedAction) 
        : 0;
    // 如果未找到匹配项，默认选中第一项
    if (_selectedIndex < 0 && widget.actions.isNotEmpty) {
      _selectedIndex = 0;
      _currentSelectedAction = widget.actions[0];
    }
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      decoration: BoxDecoration(
        color: Get.theme.colorScheme.primaryContainer,
        borderRadius: BorderRadius.only(
          topLeft: Radius.circular(16.r),
          topRight: Radius.circular(16.r),
        ),
      ),
      child: Column(
        mainAxisSize: MainAxisSize.min,
        children: [
          // 标题栏
          _buildHeader(context),
          // 内容区域
          _buildContent(context),
        ],
      ),
    );
  }

  /// 构建标题栏
  Widget _buildHeader(BuildContext context) {
    return Padding(
      padding: EdgeInsets.symmetric(horizontal: 16.w, vertical: 12.h),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        children: [
          // 取消按钮
          TextButton(
            onPressed: () {
              if (widget.onCancel != null) {
                widget.onCancel!();
              }
              // 取消时返回null
              Navigator.pop(context, null);
            },
            child: Text(
              LocaleKeys.cancel.tr,
              style: TextStyle(
                fontSize: 16.sp,
                color: Get.theme.colorScheme.onPrimary,
              ),
            ),
          ),
          // 标题
          Flexible(
            child: Text(
              textAlign: TextAlign.center,
              widget.title,
              style: TextStyle(
                fontSize: 16.sp,
                fontWeight: FontWeight.w500,
                color: Get.theme.colorScheme.primary,
              ),
            ),
          ),
          // 确认按钮
          TextButton(
            onPressed: () {
              if (widget.onConfirm != null) {
                widget.onConfirm!(_currentSelectedAction);
              }
              // 确认时返回选中的操作
              Navigator.pop(context, _currentSelectedAction);
            },
            child: Text(
              LocaleKeys.confirm.tr,
              style: TextStyle(
                fontSize: 16.sp,
                color: Get.theme.colorScheme.primaryFixed,
              ),
            ),
          ),
        ],
      ),
    );
  }

  /// 构建内容区域
  Widget _buildContent(BuildContext context) {
    // 固定高度的选择器
    final pickerHeight = 200.h;
    
    return Container(
      height: pickerHeight,
      padding: EdgeInsets.symmetric(horizontal: 16.w),
      child: Stack(
        children: [
          // 中间选中区域的高亮
          Positioned.fill(
            child: Center(
              child: Container(
                height: 52.h,
                decoration: BoxDecoration(
                  color: Get.theme.colorScheme.primary.withOpacity(0.1),
                  borderRadius: BorderRadius.circular(8.r),
                ),
              ),
            ),
          ),
          // 选择器
          CupertinoPicker(
            magnification: 1.2, // 选中项放大效果
            squeeze: 1.0,
            looping: false, // 是否循环滚动
            backgroundColor: Colors.transparent,
            itemExtent: 50.h, // 每个选项的高度
            selectionOverlay: Container(), // 使用自定义覆盖层
            onSelectedItemChanged: (int index) {
              setState(() {
                _selectedIndex = index;
                _currentSelectedAction = widget.actions[index];
              });
            },
            scrollController: FixedExtentScrollController(
              initialItem: _selectedIndex,
            ),
            children: List<Widget>.generate(
              widget.actions.length,
              (int index) {
                // 使用displayStringForOption回调获取显示文本
                final displayText = widget.displayStringForOption(widget.actions[index]);
                return Center(
                  child: Text(
                    displayText,
                    style: TextStyle(
                      fontSize: 18.sp,
                      fontWeight: _selectedIndex == index ? FontWeight.bold : FontWeight.normal,
                      color: _selectedIndex == index 
                          ? Get.theme.colorScheme.primary
                          : Get.theme.colorScheme.secondary,
                    ),
                  ),
                );
              },
            ),
          ),
        ],
      ),
    );
  }

  /// 显示耳机操作弹窗
  ///
  /// 返回用户选择的操作值，如果用户取消则返回null
}